<?php

namespace app\service;

class poster
{
    public static function make($bgImgPath, $element, $targetImg)
    {
        if (file_exists($targetImg)) {
            unlink($targetImg);
        }
        $img = imagecreatefromstring(request($bgImgPath));
        $avatarImg = imagecreatefromstring(request($element['avatar']));
        $qrcodeImg = imagecreatefromstring(request($element['qrcode']));
        if (!$img) {
            throw new \Exception('找不到海报背景图片');
        }
        if (!$avatarImg) {
            throw new \Exception('找不到用户头像');
        }
        if (!$qrcodeImg) {
            throw new \Exception('找不到海报二维码图片');
        }
        list($bgWidth, $bgHight, $bgType) = getimagesize($bgImgPath);
        // list($qrcodeWidth, $qrcodeHight) = getimagesize($element['qrcode']);
        // list($avatarWidth, $avatarHight) = getimagesize($element['avatar']);
        $avatarWidth = ImageSX($avatarImg);
        $avatarHight = ImageSY($avatarImg);
        $qrcodeWidth = ImageSX($qrcodeImg);
        $qrcodeHight = ImageSY($qrcodeImg);

        $font = APP_PATH . "/public/fonts/fz.TTF";
        $black = imagecolorallocate($img, 0x33, 0x33, 0x33);
        $red = imagecolorallocate($img, 0x33, 0x33, 0x33);
        imagettftext($img, 24, 0, ceil(($bgWidth - mb_strlen($element['nickname']) * 27) / 2), 280, $black, $font, $element['nickname']);
        imagettftext($img, 24, 0, ceil(($bgWidth - mb_strlen($element['id']) * 20) / 2), 335, $red, $font, $element['id']);

        imagecopyresized(
            $img,
            $avatarImg,
            ceil(($bgWidth - 90) / 2),
            95,
            0,
            0,
            100,
            100,
            $avatarWidth,
            $avatarHight
        );
        imagecopy(
            $img,
            $qrcodeImg,
            ceil(($bgWidth - $qrcodeWidth) / 2),
            $bgHight - $qrcodeHight - 200,
            0,
            0,
            $qrcodeWidth,
            $qrcodeHight
        );

        // if ($returnfilepath == 0) {
        //     switch ($bgType) {
        //         case 1: //gif
        //             header('Content-Type:image/gif');
        //             imagegif($img);
        //             break;
        //         case 2: //jpg
        //             header('Content-Type:image/jpg');
        //             imagejpeg($img);
        //             break;
        //         case 3: //png
        //             header('Content-Type:image/png');
        //             imagepng($img);
        //             break;
        //     }
        //     imagedestroy($img);
        // }

        switch ($bgType) {
            case 1: //gif
                imagegif($img, $targetImg);
                break;
            case 2: //jpg
                imagejpeg($img, $targetImg);
                break;
            case 3: //png
                imagepng($img, $targetImg);
                break;
        }
        imagedestroy($img);
    }
}

